import { useEffect, useRef, useState } from 'react';
import { CourseDetail } from '@/pages/pc/components';
import { Tabs, Form, Input, Spin, Select, Popconfirm, message, Popover, Modal } from 'antd';
import classNames from 'classnames';
import { Link, useHistory, useModel } from 'umi';
import styles from './index.less';
import Pagination from '@/pages/pc/components/Pagination';
import { useForm } from 'antd/es/form/Form';
import { allGet } from '@/services/pc';
import { PlvVideoListModalUpload } from '../components/Upload';
import { BjyVideoListModalUpload } from '@/pages/pc/components/Upload';
import VideoPlayerModal from '../components/VideoPlayer';
import storage from '@/utils/storage';
import { CLASS_TYPE_MAP, COOPERATIONINFORMATION } from '@/common/const';
import Empty from '../components/Empty';
import moment from 'moment';
import { accSub } from '@/utils/math';
import { isYsClass } from '@/utils';
import WorkTable from '@/pages/pc/lecturer/upload-courses/components/table';
const { TabPane } = Tabs;

// 课程
const Courses = () => {
  const history = useHistory();
  const [data, setData] = useState<any>({});
  const [current, setCurrent] = useState(1);
  const [loading, setLoading] = useState(true);
  const pageSize = 8;
  const { userInfo } = useModel('user');
  const init = async () => {
    const response = await allGet({
      params: { mod: 'user', do: 'course', version: 'pc1.0', page: current, perpage: pageSize },
    });
    if (response.success) {
      setData(response.data || {});
    }
    setLoading(false);
  };
  useEffect(() => {
    init();
  }, [current]);
  const handlePageChange = (page) => {
    setCurrent(page);
  };
  const courseDetailType = (detail) => {
    if (detail?.bookprice > 0 && moment(detail?.bookdead, 'X').isSameOrAfter(moment())) {
      return 2;
    }
    if (detail.secskills?.secskillprice) {
      return 1;
    }
    if (detail.type == 8) {
      return 2;
    }
    return 3;
  };

  const renderStatus = (item) => {
    if (item.status == '-1') {
      return <div className={classNames(styles.status, styles.status1)}>审核中</div>;
    }
    if (item.status == '-2') {
      return <div className={classNames(styles.status, styles.status2)}>未通过</div>;
    }
    if (item.status == 1) {
      return <div className={classNames(styles.status, styles.status3)}>已上线</div>;
    }
    return null;
  };
  const renderPrice = (item) => {
    if (
      (item?.bookprice > 0 && moment(item?.bookdead, 'X').isSameOrAfter(moment())) ||
      item.type == 8
    ) {
      return (
        <div className={styles.prices}>
          <div className={styles.top}>预售价：¥{item.bookprice}</div>
          <div className={styles.bottom}>¥{item.price}</div>
        </div>
      );
    }
    if (item.secskills?.secskillprice) {
      return (
        <div className={styles.prices}>
          <div className={styles.top}>秒杀价：¥{item?.secskills?.secskillprice}</div>
          <div className={styles.bottom}>¥{item.price}</div>
        </div>
      );
    }
    return <div className={styles.prices}>¥{item.price}</div>;
  };

  const [baomingShow, setBaomingShow] = useState(false);
  const [yishouShow, setYishouShow] = useState(false);

  // 布置作业
  const [workTableVisible, setWorkTableVisible] = useState<boolean>(false);
  const [workTableLoading, setWorkTableLoading] = useState<boolean>(true);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [currentClassid, setCurrentClassid] = useState('');
  // 获取详情
  const getDetails = async (classId) => {
    setWorkTableLoading(true);
    const response = await allGet({
      params: { mod: 'course', do: 'post', version: 'pc1.0', classid: classId /* classid */ },
    });
    if (response.success) {
      const { chapters = [] } = response.data;
      // console.log(2222, allCl);
      const chapters_1: any[] = [];
      let othersLessons_1: any[] = [];
      chapters.forEach((item, index) => {
        if (Number(item.cid) === 0) {
          othersLessons_1 = (item.children ?? []).map((it, i, arr) => {
            if (i > 0) {
              it.beforeIndex = arr[i - 1].displayorder;
            }
            if (i < arr.length - 1) {
              it.afterIndex = arr[i + 1].displayorder;
            }
            return it;
          });
        } else {
          chapters_1.push({
            ...item,
            children: (item.children ?? []).map((it, i, arr) => {
              if (i > 0) {
                it.beforeIndex = arr[i - 1].displayorder;
              } else if (i < arr.length - 1) {
                it.afterIndex = arr[i + 1].displayorder;
              }
              return it;
            }),
          });
        }
      });
      setDataSource([...chapters_1, ...othersLessons_1]);
      setWorkTableLoading(false);
    }
  };
  const handleAddWorks = async (item) => {
    setCurrentClassid(item.classid);
    await getDetails(item.classid);
    setWorkTableVisible(true);
  };

  // 关闭作业弹窗
  const onCloseWorkTable = () => {
    setWorkTableVisible(false);
    setDataSource([]);
  };

  return (
    <div className={styles.courses}>
      {loading ? null : data?.list?.length > 0 ? (
        <table className={styles.table}>
          <thead>
            <tr>
              <th>课程信息</th>
              <th>课程类型</th>
              <th>浏览量</th>
              <th>课时数</th>
              <th>售价</th>
              <th>
                <div className={styles.yan}>
                  报名
                  <i
                    className={classNames(styles.icon, { [styles.actived]: baomingShow })}
                    onClick={() => setBaomingShow(!baomingShow)}
                  />
                </div>
              </th>
              <th>
                <div className={styles.yan}>
                  已售
                  <i
                    className={classNames(styles.icon, { [styles.actived]: yishouShow })}
                    onClick={() => setYishouShow(!yishouShow)}
                  />
                </div>
              </th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {data?.list?.map((item) => {
              return (
                <tr key={item.classid}>
                  <td width="30%">
                    <div className={styles.kc}>
                      <div
                        className={styles.left}
                        onClick={() => window.open(`/center/courses/detail/${item.classid}`)}
                      >
                        <img src={item.pic} alt="" className={styles.img} />
                        <div className={styles.name}>{item.name}</div>
                      </div>
                      {renderStatus(item)}
                    </div>
                  </td>
                  <td>
                    {isYsClass(item)
                      ? '预售课'
                      : CLASS_TYPE_MAP[item.type] || <div className={styles.empty}>-</div>}
                  </td>
                  <td>{item.viewnum}</td>
                  <td>{item.lessonnum}</td>
                  <td>{renderPrice(item)}</td>
                  <td>{baomingShow ? item.enrollnum : '***'}</td>
                  <td>{yishouShow ? item.studentnum : '***'}</td>
                  <td>
                    <div className={styles.buttons}>
                      {Number(item.unratenum) > 0 && (
                        <div
                          className={styles.button}
                          onClick={() => window.open(`/lecturer/works?classId=${item.classid}`)}
                        >
                          学员作业 <div className={styles.dot}>{item.unratenum}</div>
                        </div>
                      )}
                      <div className={styles.button} onClick={() => handleAddWorks(item)}>
                        布置作业
                      </div>
                      <div
                        className={styles.button}
                        onClick={() =>
                          history.push(`/center/upload-courses?classid=${item.classid}`)
                        }
                      >
                        编辑课程
                      </div>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      ) : (
        <Empty text="暂无课程">
          <div className={styles.upload} onClick={() => history.push('/center/upload-courses')}>
            <img
              className={styles.icon}
              src={require('@/assets/pc/images/index/icon-upload.png')}
            />
            上传课程
          </div>
        </Empty>
      )}
      <Modal
        wrapClassName="c-lecturer-chapter-modal-wrap-container"
        visible={workTableVisible}
        footer={false}
        onCancel={onCloseWorkTable}
        destroyOnClose
        width={800}
        maskClosable={false}
      >
        <WorkTable
          key={currentClassid}
          isModal
          loading={workTableLoading}
          classid={currentClassid}
          reload={getDetails}
          dataSource={dataSource}
        />
      </Modal>
      {/* {loading ? null : data?.list?.length > 0 ? (
        data?.list?.map((item) => {
          return (
            <div className={styles.item} key={item.classid}>
              <CourseDetail
                type={courseDetailType(item)}
                role={2}
                data={item}
                showApplyStatus
                classId={item.classid}
                onClick={() => window.open(`/center/courses/detail/${item.classid}`)}
              />
            </div>
          );
        })
      ) : (
        <Empty text="暂无课程">
          <div className={styles.upload} onClick={() => history.push('/center/upload-courses')}>
            <img
              className={styles.icon}
              src={require('@/assets/pc/images/index/icon-upload.png')}
            />
            上传课程
          </div>
        </Empty>
      )} */}
      {/* <div className={styles.item}>
      <CourseDetail hasRewrad={false} type={1} role={2} />
     <div className={styles.workWrapper}>
        课程作业：
        <Link to={`/lecturer/works?id=222`} className={classNames(styles.info, styles.red)}>
          你有 <span className={styles.num}>12</span> 份作业还未批改，请前往批改。
          <i className={styles.go} />
        </Link >
      </div>
    </div>
    <div className={styles.item}>
      <CourseDetail hasRewrad={false} type={2} role={2} />

    </div>
    <div className={styles.item}>
      <CourseDetail hasRewrad={false} type={3} role={2} />

    </div> */}
      {data?.count > pageSize && (
        <Pagination
          pageSize={pageSize}
          className={styles.pagination}
          total={data?.count}
          current={current}
          onChange={handlePageChange}
        />
      )}
    </div>
  );
};

// 报表里的table
const TableList = ({ data, current, pageSize, onPageChange }) => {
  console.log(data, 'data');

  const handlePageChange = (page: number, pageSize: number) => {
    onPageChange(page);
  };

  return (
    <>
      {data?.data?.list?.length > 0 ? (
        <div className={styles.tableWrapper}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th>付款时间</th>
                <th>课程名称</th>
                <th>学号</th>
                <th>用户名</th>
                <th>课程价格</th>
                <th>活动优惠</th>
                <th>青藤分销</th>
                {/* <th>结算</th> */}
                <th>实际收入（元）</th>
              </tr>
            </thead>
            <tbody>
              {data?.data?.list?.map((item, index) => {
                const yh = Number(accSub(item.price, item.payed));
                return (
                  <tr key={item.eid}>
                    <td width={210}>{item.payline}</td>
                    <td width="20%">
                      <div className={styles.item}>
                        <i
                          className={styles.img}
                          style={{ backgroundImage: `url(${item.thumb})` }}
                        />
                        <div className={styles.right}>
                          <div className={styles.title}>{item.classname}</div>
                          {/* <div className={styles.sub}>第四十八期游戏特效</div> */}
                        </div>
                      </div>
                    </td>
                    <td>{item.studentnum}</td>
                    <td
                      className={styles.clickable}
                      onClick={() => window.open(`/personal?uid=${item.uid}`)}
                    >
                      {item.username}
                    </td>
                    <td>¥{item.price}</td>
                    <td>{yh > 0 ? `- ¥${yh}` : '-'}</td>
                    <td>{item.mentor == 0 ? '-' : `¥${item.mentor}`}</td>
                    {/* <td>
                      <span
                        className={classNames(styles.status, {
                          [styles.red]: Number(item.teacherstatus) <= 0,
                        })}
                      >
                        {' '}
                        {Number(item.teacherstatus) > 0 ? '已结算' : '未结算'}
                      </span>
                    </td> */}
                    <td>
                      {/*         <span className={styles.money}>{item.payed}</span> */}
                      <span className={styles.money}>{accSub(item.payed, item.mentor)}</span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      ) : (
        <Empty />
      )}

      {data?.data?.count > pageSize && (
        <Pagination
          pageSize={pageSize}
          className={styles.pagination}
          total={data?.data?.count}
          current={current}
          onChange={handlePageChange}
        />
      )}
    </>
  );
};

// 收入报表
const Report = () => {
  const [data, setData] = useState<any>({});
  const [reportData, setRepotData] = useState<any>({});
  const [current, setCurrent] = useState(1);
  const pageSize = 15;

  const init = async () => {
    const response = await allGet({
      params: { mod: 'teacher', do: 'student', version: 'pc1.0', page: current, perpage: pageSize },
    });
    setData(response);
    /**
     * php说第一页回返回报表数据，后面不给了
     * 只能自己记录下
     */
    if (current === 1) {
      const { list, ...report } = response?.data || {};
      setRepotData(report || {});
    }
  };

  useEffect(() => {
    init();
  }, [current]);

  /**
   * 课程数量等
   */
  const [nums, setNums] = useState<any>();
  const { userInfo } = useModel('user');
  useEffect(() => {
    if (userInfo.uid) {
      (async () => {
        const response = await allGet({
          params: { mod: 'teacher', do: 'detail', uid: userInfo.uid, version: 'pc1.0' },
        });
        setNums(response);
      })();
    }
  }, [userInfo]);

  const handlePageChange = (page) => {
    setCurrent(page);
  };

  // const lastMonthStart = moment().subtract(1, 'months').startOf('month').format('M月D日');
  // const lastMonthEnd = moment().subtract(1, 'months').endOf('month').format('M月D日');

  return (
    <div className={styles.report}>
      <div className={styles.infos}>
        <div className={classNames(styles.infoItem, styles.zong)}>
          <div className={styles.title}>课程总收入</div>
          <div className={styles.priceWrapper}>
            <span className={styles.unit}>¥</span>
            {reportData?.total}
          </div>
        </div>
        <div className={classNames(styles.infoItem, styles.bysr)} id="bysr">
          <Popover
            overlayClassName={styles['bysr-info-propover']}
            destroyTooltipOnHide
            placement="top"
            trigger="hover"
            content={
              <div className={styles.bysrInfoDetal}>
                <div className={styles.row}>1、每月的1号开始计算，在月末24凌晨结算</div>
                <div className={styles.row}>2、上月收入数据是已结算，不会再变动</div>
                <div className={styles.row}>3、本月收入数据会根据用户的购买而变动</div>
              </div>
            }
            title={() => null}
          >
            <i className={styles.iconInfo} />
          </Popover>
          <div className={styles.bysrItem}>
            <div className={styles.price}>¥{reportData?.thisMonthpay}</div>
            <div>本月收入</div>
          </div>
          <div className={styles.bysrItem}>
            <div className={styles.price}>¥{reportData?.lastMonthpay}</div>
            <div>上月收入</div>
          </div>
        </div>
        <div className={classNames(styles.infoItem, styles.kcsl)}>
          <div className={styles.kcslItem}>
            <div className={styles.num}>{nums?.data?.coursenum}</div>
            <div>课程数</div>
          </div>
          <div className={styles.kcslItem}>
            <div className={styles.num}>{nums?.data?.studentnum}</div>
            <div>学员数</div>
          </div>
          <div className={styles.kcslItem}>
            <div className={styles.num}>{nums?.data?.lessonnum}</div>
            <div>课时数</div>
          </div>
        </div>
      </div>
      {/* <div className={styles.row}>
        <div className={styles.left}>
          <div className={styles.ratio}>
            <div className={styles.content}>
              <div className={styles.title}>课程总收入</div>
              <div className={styles.price}>
                <span className={styles.unit}>¥</span>
                {reportData?.total}
              </div>
            </div>
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.row}>
            <div className={styles.month}>
              <div className={styles.ratio}>
                <div className={styles.content}>
                  <div className={styles.title}>*每月的1日开始计算，在月末 24凌晨结算</div>
                  <div className={styles.infoWrapper}>
                    <div className={styles.item}>
                      <div className={styles.price}>¥{reportData?.thisMonthpay}</div>
                      <div className={styles.text}>本月收入</div>
                      <div className={styles.tips}>（还未结算）</div>
                    </div>
                    <div className={styles.line}>
                      <i className={styles.inner} />
                    </div>
                    <div className={styles.item}>
                      <div className={styles.price}>¥{reportData?.lastMonthpay}</div>
                      <div className={styles.text}>上月收入</div>
                      <div className={styles.tips}>
                        （{lastMonthStart}～{lastMonthEnd}）
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className={styles.hb}>
              <div className={styles.ratio}>
                <div className={styles.content}>
                  <i className={styles.iconMoney} />
                  <span
                    className={classNames(styles.num, {
                      [styles.down]: reportData?.rate < 0,
                      [styles.up]: reportData?.rate >= 0,
                    })}
                  >
                    {reportData.rate}%
                    <i className={styles.icon} />
                  </span>
                  <div className={styles.title}>环比增涨</div>
                </div>
              </div>
            </div>
          </div>
          <div className={styles.nums}>
            <div className={styles.item}>
              <div className={styles.num}>{nums?.data?.lessonnum}</div>
              <div className={styles.text}>课时数</div>
            </div>
            <div className={styles.item}>
              <div className={styles.num}>{nums?.data?.studentnum}</div>
              <div className={styles.text}>学员数</div>
            </div>
            <div className={styles.item}>
              <div className={styles.num}>{nums?.data?.coursenum}</div>
              <div className={styles.text}>课程数</div>
            </div>
          </div>
        </div>
      </div> */}
      <TableList
        data={data}
        current={current}
        pageSize={pageSize}
        onPageChange={handlePageChange}
      />
    </div>
  );
};

//合同
const Contract = () => {
  const { userInfo } = useModel('user');
  const [data, setData] = useState<any>({});
  const init = async () => {
    const response = await allGet({
      params: {
        mod: 'course',
        do: 'list',
        oride: 'classid',
        perpage: 9999,
        uid: userInfo?.uid,
        version: 'pc1.0',
      },
    });
    setData(response);
  };
  useEffect(() => {
    if (userInfo.uid) {
      init();
    }
  }, [userInfo]);

  // const handleClick = () => {
  //   PreviewImg.show({
  //     data: [
  //       'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg',
  //       'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fjiaozuo.hngp.gov.cn%2Fwebfile%2Fjiaozuo%2Frootfiles%2F2018%2F07%2F11%2F1530612451091486-1530612451154263.jpg&refer=http%3A%2F%2Fjiaozuo.hngp.gov.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657705288&t=8f96217f64829057f1d4d3ce44dc94cc', 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.ptxy.gov.cn%2Fzwgk%2Fggzypz%2Fzfcg%2F202004%2FP020200422406657806259.jpg&refer=http%3A%2F%2Fwww.ptxy.gov.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657705310&t=a8482b9c2c2f8971ed6d1711a98f92f8',],
  //   })
  // }
  return (
    <div className={styles.contracts}>
      {data?.data?.list?.length > 0 ? (
        data?.data?.list?.map?.((item, index) => {
          return (
            <div className={styles.item} key={item.id}>
              <div className={styles.main}>
                <div className={styles.left}>
                  <div className={styles.ratio}>
                    <div className={styles.content}>
                      <i className={styles.img} style={{ backgroundImage: `url(${item.thumb})` }} />
                      <i className={styles.mask} />
                      <div className={styles.price}>
                        <span className={styles.unit}>¥</span>
                        {item.price}
                      </div>
                      <div className={styles.text}>{item.name}</div>
                    </div>
                  </div>
                </div>
                <div className={styles.right}>
                  <div className={styles.ratio}>
                    <div className={styles.content}>
                      <i
                        className={styles.img}
                        style={{
                          backgroundImage: `url(${require('../../../assets/pc/images/lecturer/contract-placeholder.png')})`,
                        }}
                      />
                      <div className={styles.footermask}>
                        <span> 课程合同</span>
                        <span>需线下完成签订</span>
                      </div>

                      {/* <div className={styles.ht}>
                    共有8张合同
                  </div>
                  <i className={styles.icon} onClick={handleClick} />
                  <i className={styles.mask} /> */}
                      <i className={styles.bg1} />
                      <i className={styles.bg2} />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        })
      ) : (
        <Empty />
      )}
    </div>
  );
};

const EditTile = ({ value: propsValue, vid }) => {
  const [value, setValue] = useState(propsValue);
  const [isEdit, setEdit] = useState(false);

  const handleSave = async (text) => {
    if (!text?.trim()) {
      return message.error('标题不能为空');
    }
    setEdit(false);
    allGet({ params: { mod: 'baijiayun', do: 'edit', version: 'pc1.0', vid, filename: text } });
    return;
  };

  const handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      const text = e.target.innerText;
      handleSave(text);
      e.preventDefault();
    }
  };
  const handleBlur = (e) => {
    const text = e.target.innerText;
    handleSave(text);
  };
  const handleDivClick = (e) => {
    if (isEdit) {
      e.stopPropagation();
    }
  };
  return (
    <div className={classNames(styles.editTitle, { [styles.edit]: isEdit })}>
      <div
        contentEditable={isEdit}
        onClick={handleDivClick}
        suppressContentEditableWarning
        className={styles.text}
        onKeyDown={handleKeyDown}
        onBlur={handleBlur}
      >
        {value}
      </div>
      <i
        className={styles.edit}
        onClick={(e) => {
          e.stopPropagation();
          setEdit(true);
        }}
      />
    </div>
  );
};
// 视频库
const Videos = () => {
  const [data, setData] = useState<any>({});
  const [current, setCurrent] = useState(1);
  const pageSize = 20;

  const init = async () => {
    const response = await allGet({
      params: { mod: 'baijiayun', do: 'list', version: 'pc1.0', page: current, perpage: pageSize },
    });
    setData(response);
  };
  useEffect(() => {
    init();
  }, [current]);
  const handleDelete = async (item) => {
    const response = await allGet({
      params: { mod: 'baijiayun', do: 'delete', version: 'pc1.0', vid: item.video_id },
    });
    if (!response.success) {
      return message.error(response.data || '删除失败');
    }
    init();
    return false;
  };

  const handlePageChange = (page) => {
    setCurrent(page);
  };
  const auth = async () => {
    const response = await allGet({ params: { mod: 'polyv', do: 'uploadAuth', version: 'pc1.0' } });
    return { ...(response?.data || {}), ptime: response?.data?.ts };
  };
  const handleUploadSuccess = async (_, file) => {
    // await allGet({
    //   params: {
    //     mod: 'polyv',
    //     do: 'add',
    //     version: 'pc1.0',
    //     filename: file.name,
    //     filesize: file.size,
    //     polyvvid: file?.response?.vid,
    //   },
    // });
    init();
  };

  const handleShowVideo = (item) => {
    VideoPlayerModal.showPlvVideo({
      data: [
        {
          vid: item.video_id,
        },
      ],
    });
  };
  return (
    <div className={styles.videos}>
      <div className={styles.upload}>
        <BjyVideoListModalUpload onSuccess={handleUploadSuccess}>
          +上传课时视频
        </BjyVideoListModalUpload>
      </div>

      {data?.data?.list?.length > 0 ? (
        <div className={styles.table}>
          <div className={styles.header}>
            <div className={styles.xh}>序号</div>
            <div className={styles.title}>标题</div>
            <div className={styles.handles}>操作</div>
          </div>
          <div className={styles.body}>
            {data?.data?.list?.map?.((item, index) => {
              return (
                <div key={item.video_id} className={styles.item}>
                  <div className={styles.xh}>{index + 1}</div>
                  <div className={styles.title} onClick={() => handleShowVideo(item)}>
                    <EditTile value={item.title} vid={item.video_id} />
                  </div>
                  <div className={styles.handles}>
                    <Popconfirm
                      placement="left"
                      title="删除后不可恢复, 确定删除?"
                      onConfirm={() => handleDelete(item)}
                      okText="确定"
                      cancelText="关闭"
                    >
                      <i className={styles.delete} />
                    </Popconfirm>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      ) : (
        <Empty text="暂无视频" />
      )}

      {data?.count > pageSize && (
        <Pagination
          pageSize={pageSize}
          className={styles.pagination}
          total={data?.count}
          current={current}
          onChange={handlePageChange}
        />
      )}
    </div>
  );
};

// const CooperationForm: React.FC<any> = ({ onSuccess, }) => {

//   const [form] = useForm();

//   const [submitLoading, setSubmitLoading] = useState(false);
//   const handleSubmit = async () => {
//     if (submitLoading === true) return;
//     setSubmitLoading(true);
//     try {
//       const values = await form.validateFields();

//       if (await onSuccess(values) === false) return;
//       console.log(values)
//     } catch (error) {
//       console.log(error)
//     } finally {
//       setSubmitLoading(false)
//     }

//   }

//   return <div className={styles.cooperationForm}  >
//     <div className={styles.main} >
//       <Form
//         form={form}
//         scrollToFirstError
//         className={styles.form}
//         layout="vertical"
//         name="basic"
//         autoComplete="off"
//       >
//         <Form.Item
//           className={styles.w50}
//           label="分成比例："
//           rules={[{ required: true, message: '请选择分成比例' }]}
//           name="ccc"
//         >
//           <Select placeholder="请选择">
//             <Select.Option value="demo">Demo</Select.Option>
//           </Select>
//         </Form.Item>
//         <div className="ant-row ant-form-item ">
//           <div className="ant-col ant-form-item-label">
//             <label className="ant-form-item-required" title="个人银行卡：">个人银行卡：</label>
//           </div>
//           <div className={styles.row}>
//             <Form.Item
//               className={styles.w50}
//               rules={[{ required: true, message: '请填写银行卡归属行' }]}
//               name="a"
//             >
//               <Input placeholder='银行卡归属行' />
//             </Form.Item>
//             <Form.Item
//               className={styles.w50}
//               rules={[{ required: true, message: '请填写银行卡卡号' }]}
//               name="b"
//             >
//               <Input placeholder='银行卡卡号' />
//             </Form.Item>
//             <Form.Item
//               className={styles.w50}
//               rules={[{ required: true, message: '请填写银行卡绑定的姓名' }]}
//               name="c"
//             >
//               <Input placeholder='银行卡绑定的姓名' />
//             </Form.Item>
//           </div>
//         </div>

//         <Form.Item
//           label="合同："
//           rules={[{ required: true, message: '请签署合同：', },]}
//           name="bankcard"
//         >
//           <Input placeholder='输入银行卡号' />
//         </Form.Item>

//       </Form >
//       <div className={styles.footer}>
//         <div className={classNames(styles.button, styles.submit)} onClick={handleSubmit}><Spin spinning={submitLoading} size="small" /> 提交</div>
//       </div>

//     </div >
//   </div >

// }
// 讲师资料
const TeacherInfo = () => {
  // 讲师资料
  const { lecturer, getLecturer } = useModel('lecturer');
  const [submitLoading, setSubmitLoading] = useState(false);
  const { userInfo, isInit } = useModel('user');
  // 讲师资料
  // const { lecturer, isInit, isSinged } = useModel('lecturer');

  if (isInit.current === false) return null;
  // 合同和资料都存在，说明提交过了
  //const isSubmit = isSinged && lecturer?.teacher?.bank;
  // contractstatus == 1 是已经提交过合作资料了
  const isSubmit = userInfo.teacher?.contractstatus == 1;
  const handleSubmit = async () => {
    if (submitLoading === true) return;
    setSubmitLoading(true);
    const response = await allGet({
      params: {
        mod: 'teacher',
        do: 'update',
        version: 'pc1.0',
        teachersubmit: 1,
        resume: resumeRef.current,
      },
    });
    if (!response.success) {
      return message.error(response.data);
    }
    getLecturer();
    message.success('保存成功');
    try {
    } catch (error) {
      console.log(error);
    } finally {
      setSubmitLoading(false);
    }
  };
  const resumeRef = useRef<any>('');
  useEffect(() => {
    resumeRef.current = lecturer?.teacher?.resume || '';
  }, [lecturer]);

  if (!isSubmit) {
    return <ApplyForm />;
  }
  // const { secondIndex = 2 } = ((useHistory().location) as any)?.query
  return (
    <div className={styles.teacherInfo}>
      {isInit && (
        <>
          <div className={styles.top}>
            <div className={styles.field}>
              <div className={styles.key}>身份：</div>
              <div className={styles.value}>官方合作讲师</div>
            </div>
            <div className={styles.field}>
              <div className={styles.key}>银行卡：</div>
              <div className={styles.value}>
                {lecturer?.teacher?.bankaccount} {lecturer?.teacher?.bankcard}
              </div>
            </div>
            <div className={styles.field}>
              <div className={styles.key}>合同：</div>
              <div className={classNames(styles.value, styles.contract)}>
                <div className={styles.status}>
                  <i className={styles.icon} />
                  已签订
                </div>
                <a
                  className={styles.detail}
                  href={lecturer?.teacher?.contract?.file}
                  target="_blank"
                  rel="noreferrer"
                >
                  查看合同
                  <i className={styles.icon} />
                </a>
              </div>
            </div>
          </div>
          <div className={styles.bottom}>
            <div className={classNames(styles.field, styles.resume)}>
              <div className={styles.key}>个人经历：</div>
              <div className={classNames(styles.value)}>
                <Input.TextArea
                  defaultValue={lecturer?.teacher?.resume}
                  className={styles.textarea}
                  placeholder="个人经历"
                  onChange={(e) => (resumeRef.current = e.target.value)}
                />
              </div>
            </div>
            <div className={styles.footer}>
              <div className={classNames(styles.button, styles.submit)} onClick={handleSubmit}>
                <Spin spinning={submitLoading} size="small" /> 保存工作经历
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
  // return <div className={styles.teacherInfo}>

  //   <Tabs className='my-tabs-second' defaultActiveKey={secondIndex} >
  //     <TabPane tab="个人资料" key="1">
  //       1
  //     </TabPane>
  //     <TabPane tab="合作资料" key="2">
  //       <CooperationForm />
  //     </TabPane>
  //   </Tabs>
  // </div>
};
const ApplyForm: React.FC<any> = ({ onSuccess }) => {
  // 讲师资料
  const { getLecturer, setLecturer, isSinged } = useModel('lecturer');
  const { getUseInfo } = useModel('user');
  const [form] = useForm();

  // 获取本地存储的表单缓存数据
  useEffect(() => {
    const values = storage.get(COOPERATIONINFORMATION) || {};
    form.setFieldsValue(values);
  }, []);

  useEffect(() => {
    if (isSinged) {
      form.setFieldsValue({
        contract: true,
      });
    }
  }, [isSinged, form]);

  const [submitLoading, setSubmitLoading] = useState(false);
  const handleSubmit = async () => {
    if (submitLoading === true) return;
    setSubmitLoading(true);
    try {
      const values = await form.validateFields();
      const response = await allGet({
        params: { mod: 'teacher', do: 'cooperate', version: 'pc1.0', teachersubmit: 1, ...values },
      });
      if (!response.success) {
        return message.error(response.data);
      }
      message.success('提交成功');
      //删除本地存储的表单缓存数据
      storage.remove(COOPERATIONINFORMATION);
      // 重新请求讲师资料数据
      getLecturer();
      getUseInfo();
    } catch (error) {
      console.log(error);
    } finally {
      setSubmitLoading(false);
    }
  };
  const goSign = async () => {
    if (isSinged) return;
    const response = await allGet({ params: { mod: 'teacher', do: 'contract', version: 'pc1.0' } });
    if (!response.success) {
      return message.error(response.data);
    }
    const goto = response.data?.goto;
    const backurl = encodeURIComponent(location.href);
    const fromValues = form.getFieldsValue();
    storage.set(COOPERATIONINFORMATION, fromValues);
    window.open(`${goto}${backurl}`);
    console.log(fromValues, 'fromValues');
  };
  console.log(isSinged, 'isSinged');

  return (
    <div className={styles.applyForm}>
      <div className={styles.main}>
        <h2 className={styles.title}>提交合作资料</h2>
        <Form
          form={form}
          scrollToFirstError
          className={styles.form}
          layout="vertical"
          name="basic"
          autoComplete="off"
        >
          <div className={classNames('ant-row ant-form-item', styles.myItem)}>
            <div className="ant-col ant-form-item-label">
              <label className="ant-form-item-required" title="个人银行卡：">
                个人银行卡：
              </label>
            </div>

            <Form.Item rules={[{ required: true, message: '请填写银行卡归属行' }]} name="bank">
              <Input placeholder="银行卡归属行" />
            </Form.Item>
            <Form.Item rules={[{ required: true, message: '请填写银行卡卡号' }]} name="bankcard">
              <Input placeholder="银行卡卡号" />
            </Form.Item>
            <Form.Item
              rules={[{ required: true, message: '请填写银行卡绑定的姓名' }]}
              name="bankaccount"
            >
              <Input placeholder="银行卡绑定的姓名" />
            </Form.Item>
          </div>
          <Form.Item
            label="合同："
            rules={[{ required: true, message: '请先签署合同' }]}
            name="contract"
          >
            <div
              className={classNames(styles.contract, { [styles.actived]: isSinged })}
              onClick={goSign}
            >
              <i className={styles.icon} />
              {isSinged ? '合同签署成功' : '点击前往签署合同'}
              {isSinged && <i className={styles.iconsuccess} />}
            </div>
          </Form.Item>
        </Form>
        <div className={styles.footer}>
          <div className={classNames(styles.button, styles.submit)} onClick={handleSubmit}>
            <Spin spinning={submitLoading} size="small" /> 提交
          </div>
        </div>
      </div>
    </div>
  );
};

const Index = () => {
  const { userInfo, isInit } = useModel('user');
  // 讲师资料
  // const { lecturer, isInit, isSinged } = useModel('lecturer');

  const { index = 1 } = (useHistory().location as any)?.query;

  if (isInit.current === false) return null;
  // 合同和资料都存在，说明提交过了
  //const isSubmit = isSinged && lecturer?.teacher?.bank;
  // contractstatus == 1 是已经提交过合作资料了
  const isSubmit = userInfo.teacher?.contractstatus == 1;
  const hasWorksNumber = Number(userInfo.teacher?.ratecount) > 0;
  const hasContractstatus = userInfo.teacher?.contractstatus != 1;
  // contractstatus == 1 是已经提交过合作资料了
  return (
    <div className={styles.page}>
      <Tabs defaultActiveKey={index} className={styles.mytab}>
        <TabPane
          tab={
            <div className={styles.tabtitle}>
              课程管理 {hasWorksNumber && <div className={styles.dot} />}
            </div>
          }
          key="1"
        >
          <Courses />
        </TabPane>
        <TabPane tab="收入报表" key="2">
          <Report />
        </TabPane>
        {/* <TabPane tab="合作合同" key="3">
          <Contract />
        </TabPane> */}
        {userInfo.isadmin == 1 && (
          <TabPane tab="视频库" key="4">
            <Videos />
          </TabPane>
        )}
        <TabPane
          tab={
            <div className={styles.tabtitle}>
              讲师资料 {hasContractstatus && <div className={styles.dot} />}
            </div>
          }
          key="5"
        >
          <TeacherInfo />
        </TabPane>
      </Tabs>
    </div>
  );
};

export default Index;
